using System.Collections.Generic;
using Godot;

namespace Arcane.Source.UI
{
    public partial class Toaster : VBoxContainer
    {
        private class Toast
        {
            public Node ui;
            public float life;
        }
        [Export] int maxToastCount;

        private readonly List<Toast> _toasts = [];

        private float _toastHeight;

        public override void _Notification(int what)
        {
            if (what == NotificationResized)
            {
                _toastHeight = GetRect().Size.Y / maxToastCount;
            }
        }

        public override void _Process(double delta)
        {
            for (int i = 0; i < _toasts.Count; i++)
            {
                _toasts[i].life -= (float)delta;
            }

            _toasts.RemoveAll(toast => {
                if (toast.life <= 0)
                {
                    toast.ui.QueueFree();
                    return true;
                }
                return false;
            });
        }

        public void MakeToast(string message, float timeInSeconds)
        {
            if (_toasts.Count >= maxToastCount)
            {
                _toasts[0].ui.QueueFree();
                _toasts.RemoveAt(0);
            }

            var ui = CreateUI(message);
            AddChild(ui);

            _toasts.Add(new() { ui = ui, life = timeInSeconds });
        }

        private Control CreateUI(string message)
        {
            var ui = new Control();

            var background = new ColorRect();
            background.SetAnchorsPreset(LayoutPreset.FullRect);
            background.OffsetTop = 5;
            var bgColor = Colors.Black;
            bgColor.A = 0.5f;
            background.Color = bgColor;


            var msgLabel = new Label();
            msgLabel.SetAnchorsPreset(LayoutPreset.FullRect);
            msgLabel.Text = message;
            msgLabel.HorizontalAlignment = HorizontalAlignment.Center;
            msgLabel.VerticalAlignment = VerticalAlignment.Center;
            msgLabel.AddThemeFontSizeOverride("font_size", 32);
            background.AddChild(msgLabel);

            ui.CustomMinimumSize = new(0, _toastHeight - 5);
            ui.AddChild(background);
            return ui;
        }
    }
}